// sse log
let sseChecker;
// 显示提示框
let thisToast;
// 更新服务器
let wgtUniApp = false;

// 禁用左滑退出
function sideSwipe() {
    plus.key.addEventListener('backbutton', function () {
    }, false);
}

// 请求ping信息
function setPingDelay() {
    Object.values(ScmHosts).forEach(function (i) {
        const key = Object.keys(ScmHosts).find(key => ScmHosts[key] === i);
        const $elements = $(".dropdown-item");
        $.each($elements, function (j) {
            if ($($elements[j]).attr("key") === key) {
                pingInfo(i, $($elements[j]));
            }
        });
    });
}

// 设置选择的的节点
function setHostSelect(hostValue) {
    const key = Object.keys(ScmHosts).find(key => ScmHosts[key] === hostValue);
    $(".dropdown-item").removeClass("active");
    const $elements = $(".dropdown-item");
    $.each($elements, function (i) {
        if ($($elements[i]).attr("key") === key) {
            $($elements[i]).addClass("active");
        }
    });
}

// 从内存中获取节点信息
function getHost() {
    let hosts = plus.storage.getItem("scm-base-host");
    if (!hosts) {
        setHost(hostName)
        return hostName;
    }
    return hosts;
}

// 设置节点
function setHost(value) {
    hostName = value;
    if (typeof plus === 'undefined') {
        return;
    }
    plus.storage.setItem("scm-base-host", value);
}

// 判断是否是sql输入格式
function isInputSql(inputText) {
    if (!inputText) {
        return false;
    }
    let script = inputText.replace(/\s+/g, " ").trim().toLowerCase();
    return script.startsWith("select") ||
        script.startsWith("insert") ||
        script.startsWith("update") ||
        script.startsWith("delete") ||
        script.startsWith("create") ||
        script.startsWith("truncate") ||
        script.startsWith("show") ||
        script.startsWith("alter") ||
        script.startsWith("drop") ||
        script.startsWith("use") ||
        script.startsWith("call") ||
        script.startsWith("desc") ||
        script.startsWith("describe") ||
        script.startsWith("grant") ||
        script.startsWith("revoke") ||
        script.startsWith("flush") ||
        script.startsWith("kill") ||
        script.startsWith("explain");
}

// 请求验证码
function sendCode() {
    makeFetch('/sendCode', {}, (data) => {
        $("#authInput").val(decodeBase64(JSON.parse(data).data))
    }, (error) => {
    });
}

function downloadKey() {
    // 获取外部存储的Download目录路径
    plus.nativeUI.showWaiting("正在下载中");
    let text = $("#responseMessage").text().trim();
    if (!text || text.length != 32 || typeof plus === 'undefined') {
        return;
    }
    const downloadUrl = hostName + '/downloadKey?auth=' + getAuthorization() + '&key=' + text;
    plus.downloader.createDownload(downloadUrl, {}, function (d, status) {
        plus.nativeUI.closeWaiting();
        if (status === 200) {
            plus.runtime.openFile(d.filename);
        } else {
            plus.nativeUI.alert("下载日志失败");
        }
    }).start();
}

// 请求ping信息
function pingInfo(testUrl, $ele) {
    let start = new Date().getTime();
    fetch(testUrl + "/ping", {
        method: 'POST',
        body: {}
    })
    .then(response => response.text())
    .then(data => {
        let end = new Date().getTime();
        $ele.text($ele.attr("value") + " (ping " + (end - start) + "ms) ");
    })
    .catch(error => {
        $ele.text($ele.attr("value") + " (ping 失败) ");
    });
}

// base64解码
function decodeBase64(base64) {
    return decodeURIComponent(escape(window.atob(base64)))
}

// 脚本表单提交
function uploadFormSubmit(formData) {
    toggleDisplay(true);
    makeFetch('/upload', formData, (data) => {
        toggleDisplay(false);
        setUploadKey(JSON.parse(data).msg)
        showMessage(JSON.parse(data).msg);
    }, (error) => {
        setUploadKey()
        toggleDisplay(false);
        showToast(error);
    });
}

// 上传脚本
function scriptFormSubmit(scriptData) {
    // 获取表单数据
    const formData = {
        "script": scriptData
    }
    toggleDisplay(true);
    makeFetch('/script', JSON.stringify(formData), (data) => {
        toggleDisplay(false);
        setUploadKey(JSON.parse(data).msg)
        showMessage(JSON.parse(data).msg);
    }, (error) => {
        setUploadKey()
        toggleDisplay(false);
        showToast(error)
    });
}

// 获取授权码
function getAuthorization() {
    return document.getElementById("authInput").value;
}

// 验证授权码
function validateAuthorization() {
    if (!getAuthorization()) {
        showToast("请输入授权码");
        return false;
    }
    return true;
}

// 获取环境信息
function getEvnData(validFile) {
    let formData = new FormData(document.getElementById('executeForm'));
    const formValue = {
        'fileKey': getUploadKey()
    };
    let withCheckBox = false;
    for (const pair of formData.entries()) {
        formValue[pair[0]] = pair[1] === 'on';
        if (pair[0].startsWith('mec') || pair[0].startsWith('sec') || pair[0].startsWith('mvd') || pair[0].startsWith('svd')) {
            withCheckBox = true;
        }
    }
    if (!formValue.fileKey && validFile) {
        showToast("请上传文件或输入脚本");
        return;
    }
    // 至少选择一个环境
    if (!withCheckBox) {
        showToast("至少选择一个执行环境");
        return;
    }

    formValue['script'] = $("#scriptInput").val().trim();
    return formValue;
}

// 加载错误信息
function showMessage(msg) {
    document.getElementById('responseMessage').innerHTML = msg;
}

// 错误信息延迟恢复为key
function showMessageDelay(msg) {
    showMessage(msg);
    setTimeout(() => {
        showMessage(getUploadKey());
    }, 3000);
}

function showToast(msg) {
    if (thisToast || typeof plus === 'undefined') {
        showMessageDelay(msg);
        return;
    }
    thisToast = msg;
    plus.nativeUI.toast(msg, {
        duration: 800
    });
    setTimeout(() => {
        thisToast = null;
    }, 800)
}

// 设置上传key
function setUploadKey(key) {
    document.getElementById('uploadedKey').value = key === !key ? '' : key;
}

// 获取上传key
function getUploadKey() {
    return document.getElementById('uploadedKey').value;
}

function setLogger(log) {
    if (!log) {
        $("#logger").removeClass("mb-3");
    } else {
        $("#logger").addClass("mb-3");
    }
    document.getElementById('logger').innerText = log;
}

// 切换显示
function toggleDisplay(disabled) {
    $('#authInput').prop('disabled', disabled);
    $('#fileInput').prop('disabled', disabled);
    $("#uploadBtn").prop('disabled', disabled);
    $("#shellBtn").prop('disabled', disabled);
    $("#executeBtn").prop('disabled', disabled);
    $("#scriptInput").prop('disabled', disabled);
    $("#downloadLog").prop('disabled', disabled);
    $('input[type=\'checkbox\']').prop('disabled', disabled);
    $("#cleanDataBtn").prop('disabled', disabled);
    $('#selectAll').attr('disabled', disabled);
}

// 清理界面信息
function cleanMessage() {
    showMessage('');
    setUploadKey('');
    setLogger("");
    $('input[type=\'checkbox\']').prop('checked', false);
    $('#scriptInput').val('');
    document.getElementById('fileInput').value = '';
}

// 遮罩层显示隐藏
function modalShow(show) {
    // 如果更新app期间不执行
    if (wgtUniApp) {
        return;
    }
    if (typeof plus === 'undefined') {
        return;
    }
    if (!show) {
        plus.nativeUI.closeWaiting();
        return;
    }
    plus.nativeUI.showWaiting("正在处理中");
}

// 遮罩层显示延迟隐藏
function modalHideDelay() {
    setTimeout(() => {
        modalShow(false);
    }, 1200);
}

function removeTask() {
    modalShow(true);
    makeFetch('/removeTask', {}, (data) => {
        cleanMessage();
        modalHideDelay();
        // sseClose();
    }, (error) => {
        modalHideDelay();
    });
}

function sseConnect() {
    if (sseChecker) {
        clearInterval(sseChecker);
    }
    sseChecker = setInterval(() => {

        fetch(hostName + '/sseLog', {
            method: 'GET'
        })
        .then(response => response.text())
        .then(data => {
            let logStatus = JSON.parse(decodeBase64(JSON.parse(data).data));
            let logger = logStatus.logger;
            let status = logStatus.param;
            let sqlLike = logStatus.sqlLike;

            // 处理状态信息
            handleStatus(status, sqlLike);

            // 处理日志
            handleLogger(logger);
        });
    }, 1500);
}

// 处理日志
function handleLogger(logger) {
    let inner = document.getElementById('logger').innerText;
    if (!logger) {
        return;
    }
    if (inner && inner === logger) {
        return;
    }
    setLogger(logger);
}

// 处理状态
function handleStatus(data, sqlLike) {
    modalShow(false);
    if (!data) {
        toggleDisplay(false);
    }
    // 有运行中的任务进行回显界面的选择项
    else if (data) {
        let lockBean = data;
        setUploadKey(lockBean.fileKey)
        showMessage(lockBean.fileKey);
        Object.keys(lockBean).forEach(key => {
            $("input[name='" + key + "']").prop('checked', lockBean[key]);
        });
        toggleDisplay(true);
    }
    // 展示错误信息
    else {
        showToast(data.msg);
    }
    // 显示sql
    if (!data && sqlLike) {
        // 如果用户选择了，则不重复选，防止覆盖
        let withCheckBox = false;
        let formData = new FormData(document.getElementById('executeForm'));
        for (const pair of formData.entries()) {
            if (pair[0].startsWith('mec') || pair[0].startsWith('sec') || pair[0].startsWith('mvd') || pair[0].startsWith('svd')) {
                withCheckBox = true;
            }
        }
        if (!withCheckBox) {
            setUploadKey(sqlLike.fileKey)
            showMessage(sqlLike.fileKey);
            Object.keys(sqlLike).forEach(key => {
                $("input[name='" + key + "']").prop('checked', sqlLike[key]);
            });
        }
        toggleDisplay(false);
    }
}

function makeFetch(url, json, s, e) {
    if (url.indexOf("?auth=") === -1) {
        if (url.indexOf("&") !== -1) {
            url += "&auth=" + getAuthorization();
        } else {
            url += "?auth=" + getAuthorization();
        }
    }
    if (!url.startsWith("http")) {
        url = hostName + url;
    }
    fetch(url, {
        method: 'POST',
        body: json
    })
    .then(response => response.text())
    .then(data => s(data))
    .catch(error => e(error));
}
